/*
 * @lc app=leetcode.cn id=104 lang=javascript
 *
 * [104] 二叉树的最大深度
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
// 深度优先遍历迭代版
var maxDepth = function(root) {
  if (!root) return 0
  let maxDepth = 0
  let currentDepth = 0
  let current = root
  let prev = null
  const stack = []
  while (stack.length || current) {
    // 查找最深左子树
    while (current) {
      currentDepth++
      stack.push(current)
      current = current.left
    }
    maxDepth = Math.max(currentDepth, maxDepth)
    current = stack.pop()
    // 右子树访问完毕，那么就回到上一个节点，
    // 并将这个节点标记为右子树访问完毕
    if (!current.right || current.right === prev) {
      prev = current
      current = null
      currentDepth--
    }
    // 如果回溯发现有右子树，
    // 那么把这个节点再push回栈
    // 并且当前的depth也不需要减小
    else {
      stack.push(current)
      current = current.right
    }
  }
  return maxDepth
};
// @lc code=end

// 递归版
// var maxDepth = function(root) {
//   if (!root) return 0
//   let maxDepth = 0
//   const getDepth = (node, depth = 1) => {
//     if (depth > maxDepth) maxDepth = depth
//     if (node.left) {
//       getDepth(node.left, depth + 1)
//     }
//     if (node.right) {
//       getDepth(node.right, depth + 1)
//     }
//   }
//   getDepth(root)
//   return maxDepth
// };